package com.xiaoq.matrix.toutiao.util;

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.xiaoq.web.DefaultMapper;



@SuppressWarnings("deprecation")
public class TouTiaoOauth extends TouTiao {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3191728996019164026L;
	
	private Logger logger = LoggerFactory.getLogger(TouTiaoOauth.class);
	
	public String authorize(String response_type, String state)
			throws TouTiaoException {
		return TouTiaoConfig.getValue("authorize_url").trim() + "?client_id="
				+ TouTiaoConfig.getValue("client_key").trim() + "&redirect_uri="
				+ TouTiaoConfig.getValue("redirect_uri").trim()
				+ "&response_type=" + response_type 
				+ "&state=" + state+ "&auth_only=1";
	}
	public TouTiaoTokenStatus getAccessTokenByCode(String code){
		String accessTokenURL = TouTiaoConfig.getValue("accessToken_url");
		String accessToken = accessTokenURL+"?code="+code
				+"&client_key="+TouTiaoConfig.getValue("client_key")
				+"&client_secret="+TouTiaoConfig.getValue("client_sercret")
				+"&grant_type=authorize_code";
		HttpGet request = new HttpGet(accessToken);
		HttpClient httpClient = new DefaultHttpClient();
		TouTiaoTokenStatus tokenStatus = null;
		try {
			HttpResponse response = httpClient.execute(request);
			HttpEntity entity =response.getEntity();
			String body = EntityUtils.toString(entity, "utf-8");
			ObjectMapper objectMapper = new DefaultMapper();
			tokenStatus = objectMapper.readValue(body, TouTiaoTokenStatus.class);
			return tokenStatus;
			
		} catch (ClientProtocolException e) {
			logger.error("客户端协议异常", e);
		} catch (IOException e) {
			logger.error("IO异常", e);
		}
	
		return null ;
	}
	


}
